package com.cheer.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.URLUtil;
import com.cheer.exception.ServiceException;
import com.google.errorprone.annotations.Var;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

public class FileDownUtil {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(FileDownUtil.class);


    /**
     * 下载临时文件（下载之后删除文件）
     * @param delTemplate  临时文件夹路径
     * @param file 下载的zip文件
     * @param fileName 下载的文件名
     */
    public static void downTemporaryFile( String delTemplate, File file, String fileName) {

        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10,
                new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build());
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();

        try ( InputStream inputStream = new FileInputStream(file);

              OutputStream outputStream = response.getOutputStream() ) {

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ";filename*=UTF-8''" +
                    URLUtil.encode(fileName));
            IOUtils.copy(inputStream, outputStream);
            logger.info("文件下载成功！");
            outputStream.flush();


        }
        catch (IOException ioException){
            logger.error("+++++ io异常 +++++{}", ioException.getMessage());
        } catch (Exception e) {
            logger.error("+++++ exception异常 +++++ {}", e.getMessage());
            throw new ServiceException("文件下载异常！");
        } finally {
            try {
                File delFile = new File(delTemplate);
                // 该集合共三个元素 索引为0的是讲师列表.xlsx  索引为1的是讲座信息文件夹  索引为2的是讲座表.xlsx
                String[] length3List = delFile.list();

                // 先删除两个文件
                FileUtil.del(delTemplate+ length3List[0]);
                FileUtil.del(delTemplate+ length3List[2]);

                // 删除讲座信息文件夹
                File fileBig = new File(delTemplate + length3List[1]);
                String[] bigList = fileBig.list();
                if (bigList != null) {
                    for (String folderName : bigList) {
                        executor.execute(
                                ()-> FileUtil.del(fileBig.getPath()+"\\"+folderName)
                        );
                    }
                }
            } catch (IORuntimeException e) {
                e.printStackTrace();
                executor.shutdown();

            }

            // 等待线程执行完毕 关闭线程池
            executor.shutdown();

        }
    }

}
